﻿$(function () {
	$('a', '#cashFlowListNavigation').button();
	$('#errorIndicator').hide();

	$('#cashFlowListNavigation .cfMonthNav').click(function () {
		var nav = $(this).attr('nav');
		refreshCashFlow(nav);
	});

});

var refreshCashFlow = function (nav) {
	var monthControl = $('#monthValue');
	var monthValue = monthControl.val();

	var bindModel = function (model) {

		monthControl.val(model.MonthValue);
		$('#monthLabel').text(model.MonthLabel);
		$('#beginningBalance').text(model.BeginningBalance);
		$('#endingBalance').text(model.EndingBalance);

		$("#cashFlowTable").find("tr:gt(0)").remove();
		$("#cashFlowRowTmpl").tmpl(model.Items).appendTo("#cashFlowTable");
	};

	var getAndBindModel = function (nav) {
		$.getJSON(
			'/CashFlow/GetCashFlow',
			{ month: monthValue, nav: nav },
			bindModel
		);
	};

	$("#InitialBalanceDate").datepicker();
	$('#initialBalanceSave').click(function () {
		var date = $('#InitialBalanceDate').val();
		var amount = $('#InitialBalanceAmount').val();

		$.post(
				"/Tenant/InitialBalance",
				{
					date: date,
					amount: amount
				},
				function (data) {
					refreshCashFlow('next');
				});

	});

	getAndBindModel(nav);
}